<template>
  <div class="header-pack">
    <el-drawer
      v-model="drawerLandingPage"
      title="选择落地页"
      size="55%"
      class="native-anchor-drawer"
      direction="rtl"
      @close="handleDrawerClose(false)"
    >
      <div class="header-pack-content">
        <div class="header-pack-content-item">
          <el-form :model="form" label-width="120px" label-position="left" :rules="rules" ref="formRef">
            <el-form-item label="落地页类型" prop="headerPackLayout">
              <el-radio-group v-model="landingPageType">
                <el-radio-button label="1"> 橙子落地页 </el-radio-button>
                <el-radio-button label="2"> 手动填写 </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="落地页分配方式" prop="headerPackLayout" @change="handleUrleChange">
              <el-radio-group v-model="distributionMethods">
                <el-radio-button label="1"> 全部相同 </el-radio-button>
                <el-radio-button label="2"> 按账户分配 </el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="输入落地页" prop="landingPage" v-if="landingPageType == 2 && distributionMethods == 1">
              <el-input v-model="form.url" placeholder="请输入落地页" />
            </el-form-item>
          </el-form>
          <div class="header-pack-list">
            <MultiAccount
              ref="mircoappRef"
              :advertiserId="props.userList"
              @getAppInfo="getAppInfo"
              v-if="distributionMethods == 2"
              :landingPageType="landingPageType"
              :distributionMethods="distributionMethods"
              @landingPageUrl="handleLandingPageUrl"
            />
            <!-- @row-click="handleRowClick"
              @select-all="handleSelectAll"
              @select="handleSelect" -->
            <el-table
              :data="titleWrapList"
              ref="tableRef"
              v-if="distributionMethods == 1 && landingPageType == 1"
              @row-click="handleRowClick"
              @selection-change="handleSelectionChange"
              v-loading="loading"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="siteId" label="落地页ID" />
              <el-table-column prop="siteType" label="类型">
                <template #default="scope">
                  {{ scope.row.siteType == 'MICRO_APP' ? '小程序' : '微信小程序组件' }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="落地页名字" />
            </el-table>
          </div>
          <pagination
            v-if="total > 0 && distributionMethods == 1 && landingPageType == 1"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleGetTitleWrapList()"
          />
        </div>
        <!-- <el-dialog v-model="isLandingPageLibrary" title="标题列表" width="50%" append-to-body :close-on-click-modal="true">
          <div class="header-pack-library">
            <el-table :data="titleList" style="width: 100%">
              <el-table-column prop="id" label="ID" />
              <el-table-column prop="name" label="标题" />
            </el-table>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="isLandingPageLibrary = false">关 闭</el-button>
            </span>
          </template>
        </el-dialog> -->
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDrawerClose(false)">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { getSiteList, productUrlList } from '@/api/advertising/landingPage';
import { listSite } from '@/api/advertisement/site';
import { useAppStore } from '@/store/modules/app';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['drawerLandingPage', 'accountList', 'userList', 'drawerLandingPageList', 'type', 'productName', 'siteWay']);
const emit = defineEmits(['update:drawerLandingPage', 'selectedRows', 'isUnifiedHand', 'islandingMethods']);
const appStore = useAppStore();
const selectedRows = ref([]); //选中行
const userList = ref([]); //选中用户
const total = ref(0);
const isLandingPageLibrary = ref(false);
const mircoappRef = ref();
const tableRef = ref();
const drawerLandingPage = ref(false);
const landingPageType = ref('1'); //落地页类型
const distributionMethods = ref(props.siteWay || '1'); //落地页分配方式
const titleWrapList = ref([]); //标题包列表
const titleList = ref([]); //标题包下标题列表
const loading = ref(false);
const initFormData: any = {
  userInfo: [],
  url: ''
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserId: undefined
  }
});
const { form, queryParams, rules, groupQos } = toRefs(data);

watch(
  () => props.type,
  () => {
    landingPageType.value = props.type === 'AWEME' || props.type === 'BYTE_APP' ? '2' : '1';
  },
  {
    immediate: true
  }
);
watch(
  () => props.drawerLandingPage,
  (val) => {
    nextTick(async () => {
      drawerLandingPage.value = val;
      await hadleGetSiteList();
      if (props.drawerLandingPage && props.type === 'AWEME') {
        await handleGetProductUrlList();
      }
    });
  },
  { immediate: true }
);
// watch(
//   () => drawerLandingPage.value,
//   (val) => {
//     emit('update:drawerLandingPage', val);
//     hadleGetSiteList();
//   }
// );
const handleUrleChange = (val) => {
  form.value.userInfo.map((itm) => {
    itm.url = '';
  });
  mircoappRef.value?.allClearUserAppInfo();
};
const handleSelectionChange = (selection) => {
  if (selection.length > 1) {
    // 取消之前的选择
    tableRef.value.clearSelection();
    // 只保留最后一个选择
    tableRef.value.toggleRowSelection(selection[selection.length - 1]);
    selectedRows.value = selection[selection.length - 1];
  } else {
    selectedRows.value = selection.length ? selection[0] : null;
  }
};
//
const handleLandingPageUrl = (val) => {
  if (landingPageType.value == 2 && distributionMethods.value == 2) {
    selectedRows.value = val;
  }
};
/**
 * 获取小程序信息
 */
const getAppInfo = (val: SelectAppInfoType[]) => {
  selectedRows.value = val;
  console.log(val, 'val666');
};
const handleDrawerClose = (val: boolean) => {
  drawerLandingPage.value = val;
  emit('update:drawerLandingPage', val);
};

const hadleGetSiteList = async () => {
  queryParams.value.advertiserId = props.accountList[0]?.id;
  loading.value = true;
  const res = await listSite(queryParams.value);
  titleWrapList.value = res.rows;
  nextTick(() => {
    if (distributionMethods.value == 1 && landingPageType.value == 1) {
      titleWrapList.value.forEach((item: any) => {
        props.drawerLandingPageList &&
          props.drawerLandingPageList.forEach((item1: any) => {
            if (item.name === item1.name) {
              tableRef.value.toggleRowSelection(item, true);
            }
          });
      });
    } else if (landingPageType.value == 2 && distributionMethods.value == 1) {
      form.value.url = props.drawerLandingPageList[0]?.url || '';
    }
  });
  total.value = res.total;
  loading.value = false;

  // await listSite(queryParams.value).then((res) => {
  //   if (res.code === 200) {
  //     titleWrapList.value = res.rows;
  //     nextTick(() => {
  //       if (distributionMethods.value == 1 && landingPageType.value == 1) {
  //         titleWrapList.value.forEach((item: any) => {
  //           props.drawerLandingPageList &&
  //             props.drawerLandingPageList.forEach((item1: any) => {
  //               if (item.name === item1.name) {
  //                 tableRef.value.toggleRowSelection(item, true);
  //               }
  //             });
  //         });
  //       }
  //     });
  //     total.value = res.total;
  //   }
  // });
};
const handleRowClick = (row) => {
  // 切换当前行的选中状态
  row.flag = !row.flag;
  tableRef.value.toggleRowSelection(row);
};
//如果是抖音号，就要调用这个接口，如果落地页没有默认就显示这个接口的地址默认进去
const handleGetProductUrlList = async () => {
  if (!props.productName) return;
  console.log(props.productName, 'props.productName');

  let params = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    name: props.productName
  };

  const res = await productUrlList(params);
  if (res.code === 200) {
    form.value.url = res.rows[0].url;
  }
};
const handleSubmit = () => {
  // if (!tableRef.value?.getSelectionRows().length) {
  //   ElMessage({
  //     message: '请选择素材',
  //     type: 'error'
  //   });
  //   return;
  // }
  // 全部相同的手动填写
  if (landingPageType.value == 2 && distributionMethods.value == 1) {
    if (!form.value.url) {
      ElMessage({
        message: '请输入落地页链接',
        type: 'error'
      });
      return;
    }
    userList.value = props.userList;
    userList.value.map((item) => {
      item.url = form.value.url;
      item.advertiserId = item.id;
    });
    selectedRows.value = userList.value;
  }
  if (landingPageType.value == 1 && distributionMethods.value == 2) {
    if (selectedRows.value.length == 0) {
      ElMessage({
        message: '请选择落地页链接',
        type: 'error'
      });
      return;
    }
    if (selectedRows.value.some((item) => !item.url)) {
      ElMessage({
        message: '还有未选择的落地页链接',
        type: 'error'
      });
      return;
    }
  }
  // 分别账号的手动填写
  if (landingPageType.value == 2 && distributionMethods.value == 2) {
    if (selectedRows.value.some((item) => !item.url)) {
      ElMessage({
        message: '还有未输入的落地页链接',
        type: 'error'
      });
      return;
    }
  }
  if (landingPageType.value == 1 && distributionMethods.value == 1) {
    const selectedRows = tableRef.value.getSelectionRows();
    let newSelectedRows = JSON.parse(JSON.stringify(props.userList));
    newSelectedRows.map((item) => {
      selectedRows.map((itm) => {
        (item.advertiserId = item.id), (item.url = itm.url), (item.name = itm.name);
      });
    });
    emit('selectedRows', { rows: newSelectedRows, siteWay: distributionMethods.value });
  } else {
    emit('selectedRows', { rows: selectedRows.value, siteWay: distributionMethods.value });
  }
  let isUnifiedHand = landingPageType.value == 2;
  let islandingMethods = landingPageType.value == 1 && distributionMethods.value == 2;
  emit('isUnifiedHand', isUnifiedHand);
  emit('islandingMethods', islandingMethods);
  // selectedRows.value = form.value.userInfo;
  if (props.videoTotals < selectedRows.length) {
    ElMessage({
      message: '视频数量不能超过数量规定的最大值，请先设置总数',
      type: 'error'
    });
    return;
  }
  emit('update:drawerLandingPage', false);

  drawerLandingPage.value = false;
};
</script>

<style scoped lang="scss">
::v-deep(.el-radio-button__original-radio:disabled:checked + .el-radio-button__inner) {
  background-color: #409eff !important;
  color: #fff !important;
}
.header-pack {
  .header-pack-content {
    padding: 0 20px;
    .header-pack-content-item {
      .el-radio-group {
        :deep(.el-radio-button__inner) {
          display: flex;
          flex-direction: column;
        }
        span {
          display: block;
          &:first-child {
            font-size: 14px;
            font-weight: 600;
            padding-bottom: 10px;
          }
          &:last-child {
            font-size: 12px;
          }
        }
      }
    }
    .header-pack-list {
      margin-top: 20px;
    }
  }
}
</style>
